#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2018/7/28 16:09
@Author  : tonychao
@File    : daemon_fromDB.py
功能：使用： daemon_fromDB.py app_md5 className
"""


def OutPut(line):
    print ("[python ]:\t"+line)
    sys.stdout.flush()

#当前脚本目录
import sys,os
ScriptPath = os.path.split( os.path.realpath( sys.argv[0] ) )[0]
ScriptPath=ScriptPath+'/'
OutPut("current work path："+ScriptPath)

import time
import DBReader

#获得数据 主要是数据标准化的问题没法回避
app_md5=sys.argv[1]
className=sys.argv[2]
OutPut("…………")
inputConf1,inputConf2,inputConf3,runTime1,runTime2,runTime3,totalRunTime= DBReader.readDB(app_md5,className)

# 数据标准化 Standardize features by removing the mean and scaling to unit variance
from sklearn.preprocessing import StandardScaler
X_scaler1 = StandardScaler();X_scaler2 = StandardScaler();X_scaler3 = StandardScaler();
X_scaler1.fit(inputConf1);X_scaler2.fit(inputConf2);X_scaler3.fit(inputConf3);
OutPut("数据标准化完成")

from sklearn.externals import joblib  # save the model in a file

OutPut("读取分层模型")
modelPath=ScriptPath + 'savedModels/'+app_md5+"_"+className+"/"
OutPut("model path:"+modelPath)
model1=joblib.load(modelPath+"stageModel_0.pkl")
model2=joblib.load(modelPath+"stageModel_1.pkl")
model3=joblib.load(modelPath+"stageModel_2.pkl")
sys.stdout.flush()

'''
守护进程开一个不停止的循环，使用标准输入和标准输出进行数据交互
'''
OutPut("prediction model start!")
while True:
     str= raw_input("Enter your input: ");
     input_list=str.split(' ')
     #print  input_list
     test_list=[]
     for s in input_list:
          if s!="":
               test_list.append(eval(s))
#     print "test_list"
     print test_list
     list1=test_list[:11]
     list2=test_list[11:12]
     list3=test_list[12:13]

     list1=X_scaler1.transform([list1])
     list2=X_scaler2.transform([list2])
     list3=X_scaler3.transform([list3])
     #执行预测，但是仅仅返回一个结果


     ret1 = model1.predict(list1)[0]

     ret2 = model2.predict(list2)[0]
     ret3 = model3.predict(list3)[0]
     print  ('[prediction results]:\t%d\t%d\t%d'%(round(ret1*10000),round(ret2*10000),round(ret3*10000)))
     sys.stdout.flush()
#48 1 0 3072 5120 1 0 12 2 0 70

